package local.blueheart.data.springdatademo.security;

import local.blueheart.data.springdatademo.domain.system.AppUser;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class AppUsrePrincipal implements UserDetails {

    public AppUsrePrincipal(AppUser user) {
        this.user = user;
    }

    private final AppUser user;


    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<GrantedAuthority> grantedAuthorityList = new ArrayList<>();
        user.getAppRoles().forEach(appRole -> {
            grantedAuthorityList.add(new SimpleGrantedAuthority(appRole.getRole()));
        });
        if(grantedAuthorityList.isEmpty()){
            //默认加入一个USER角色
            grantedAuthorityList.add(new SimpleGrantedAuthority("USER"));
        }
        return grantedAuthorityList;
    }

    @Override
    public String getPassword() {
        return user.getEncryptedPassword();
    }

    @Override
    public String getUsername() {
        return user.getUsername();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }

    public AppUser getUser() {
        return user;
    }
}
